package com.twang.stock.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.dto.BaseRequest;
import com.twang.stock.dto.ZuoYeSumbitDto;
import com.twang.stock.entity.ZuoYeRank;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.UserService;
import com.twang.stock.service.ZuoYeRankService;
import com.twang.stock.service.ZuoYeSumbitService;
import com.twang.stock.service.jinyan.CommonService;
import com.twang.stock.utils.date.DateUtils;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 交作业
 */
@Controller
@RequestMapping(value = "/ebaybs")
@Slf4j
public class EbayBaoXiaoController {

    @Autowired
    private ZuoYeSumbitService zuoYeSumbitService;

    @Autowired
    private ZuoYeRankService zuoYeRankService;


    // 注入HttpSession
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private CommonService commonService;



    @RequestMapping(value = "baodan")
    public ModelAndView addon(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("ebay/bs/index");
        return modelAndView;
    }

    @RequestMapping(value = "reRank")
    public ModelAndView reRank(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        zuoYeRankService.doRank();
        return modelAndView;
    }

    @RequestMapping(value = "importData")
    public ModelAndView importData(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        zuoYeSumbitService.importData();
        return modelAndView;
    }

    @RequestMapping(value = "userList")
    public ModelAndView userList() {
        ModelAndView modelAndView = new ModelAndView();
        List<ZuoYeRank> zuoYeRanks = zuoYeRankService.getRankList();
        modelAndView.addObject("zuoYeRanks", zuoYeRanks);
        modelAndView.setViewName("zy/rank");
        return modelAndView;
    }

    @GetMapping(value = "queryUserByIdName")
    public ModelAndView queryUserByIdName(String userName) {
        ModelAndView modelAndView = new ModelAndView();
        List<ZuoYeRank> zuoYeRanks = zuoYeRankService.queryByName(userName);
        modelAndView.addObject("zuoYeRanks", zuoYeRanks);
        modelAndView.setViewName("zy/userInfoList");
        return modelAndView;
    }

    /**
     * 跳转新增用户
     * @return
     */
    @GetMapping(value = "initAddNewUser")
    public ModelAndView initAddNewUser() {
        ModelAndView modelAndView = new ModelAndView();
        Object token = httpSession.getAttribute(UserService.TOKEN);
        Boolean isLogin = Boolean.FALSE;
        if (null != token) {
            String token1 = redisUtil.get(token.toString()).toString();
            if (token.toString().equals(token1.toString())) {
                isLogin = Boolean.TRUE;
            }
        }
        //
        if (isLogin) {
            modelAndView.setViewName("zy/addNewUser");
        } else {
            modelAndView.addObject("success", "您没有操作权限，请先登录！");
            modelAndView.setViewName("zy/success");
        }
        return modelAndView;
    }
    @RequestMapping(value = "addNewUser")
    public ModelAndView addNewUser(ZuoYeRank zuoYeRank) {

        ModelAndView modelAndView = new ModelAndView();
        Object token = httpSession.getAttribute(UserService.TOKEN);
        Boolean isLogin = Boolean.FALSE;
        if (null != token) {
            String token1 = redisUtil.get(token.toString()).toString();
            if (token.toString().equals(token1.toString())) {
                isLogin = Boolean.TRUE;
            }
        }
        //
        if (isLogin) {
            zuoYeRankService.addUser(zuoYeRank);
            modelAndView.addObject("success", "新增成功！");
        } else {
            modelAndView.addObject("success", "您没有操作权限，请先登录！");
        }
        modelAndView.setViewName("zy/success");
        return modelAndView;
    }




    @GetMapping(value = "queryUserById")
    public ModelAndView queryUserById(Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        Object token = httpSession.getAttribute(UserService.TOKEN);
        Boolean isLogin = Boolean.FALSE;
        if (null != token) {
            String token1 = redisUtil.get(token.toString()).toString();
            if (token.toString().equals(token1.toString())) {
                isLogin = Boolean.TRUE;
            }
        }
        //
        if (isLogin) {
            ZuoYeRank zuoYeRank = zuoYeRankService.queryById(id);
            modelAndView.addObject("zuoYeRank", zuoYeRank);
            modelAndView.setViewName("zy/modify");
        } else {
            modelAndView.addObject("success", "您没有操作权限，请先登录！");
            modelAndView.setViewName("zy/success");
        }


        return modelAndView;
    }
    @RequestMapping(value = "/update")
    public ModelAndView update(ZuoYeRank zuoYeRank) {
        ModelAndView modelAndView = new ModelAndView();
        String message = "";
        try {
            log.info(">>>>>>>>>>> 交作业 update  request={}", JSONObject.toJSONString(zuoYeRank));
            zuoYeRankService.updateRankData(zuoYeRank);
            message = zuoYeRank.getUserName() + "，更新成功！";
        } catch (Exception e) {
            log.error(">>>>>>>>>> 交作业 update error:{}", e);
            message = "更新异常：" + e.getMessage();
        }
        modelAndView.addObject("success", message);
        modelAndView.setViewName("zy/success");
        return modelAndView;
    }


    @RequestMapping(value = "/submit")
    public ModelAndView sumbit(ZuoYeSumbitDto zuoYeSumbitDto)  {
        Object token = httpSession.getAttribute(UserService.TOKEN);
        Boolean isLogin = Boolean.FALSE;
        if (null != token) {
            String token1 = redisUtil.get(token.toString()).toString();
            if (token.toString().equals(token1.toString())) {
                isLogin = Boolean.TRUE;
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        String message="";
        String openSwitch = commonService.getValue("ZUO_YE_FIRST_SUMBIT").toString();
        String openStartTime = commonService.getValue("OPEN_START_TIME").toString();
        String openEndTime = commonService.getValue("OPEN_END_TIME").toString();
        if (!DateUtils.JudgeTime(openStartTime, openEndTime) && (!"OPEN".equals(openSwitch) && !isLogin)) {
            message= "当前时间不允许报单，可报单时间："+openStartTime+"～"+openEndTime;
        }else{
            try {
                log.info(">>>>>>>>>>> 交作业 submit  request={}", JSONObject.toJSONString(zuoYeSumbitDto));
                zuoYeSumbitService.saveData(zuoYeSumbitDto);
                message= "恭喜:" + zuoYeSumbitDto.getName() + "，提交成功";
            } catch (Exception e) {
                log.error(">>>>>>>>>> 交作业 submit error:{}",e);
                message= "提交异常："+e.getMessage();
            }
        }
        modelAndView.addObject("success",message);
        modelAndView.setViewName("zy/success");
        return modelAndView;
    }

    @GetMapping(value = "/deletedById")
    @Transactional(rollbackFor = Exception.class)
    public String deletedById(ZuoYeRank zuoYeRank) {
        Boolean result = zuoYeRankService.deletedById(zuoYeRank.getId(), zuoYeRank.getDate());
        if (!result) {
            return "删除失败";
        }
        return "删除成功";
    }

    @GetMapping(value = "/showImage")
    public ModelAndView showImage(String userName,String date,String type) {
        ModelAndView modelAndView = new ModelAndView();
        String result = zuoYeRankService.getBase64Image(userName.substring(0,4), date,type);
        modelAndView.addObject("image",result);
        modelAndView.setViewName("zy/image");
        return modelAndView;
    }

    @GetMapping("/initUpload")
    public ModelAndView initUpload() {
        Object token = httpSession.getAttribute(UserService.TOKEN);
        Boolean isLogin = Boolean.FALSE;
        if (null != token) {
            String token1 = redisUtil.get(token.toString()).toString();
            if (token.toString().equals(token1.toString())) {
                isLogin = Boolean.TRUE;
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        if(isLogin){
            modelAndView.setViewName("zy/importFile");
        }else{
            modelAndView.addObject("success","请先登录！");
            modelAndView.setViewName("zy/success");
        }
        return modelAndView;
    }


    @PostMapping("/upload")
    public ModelAndView uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        if (file.isEmpty()) {
            modelAndView.addObject("success","请先上传文件！");
        }else{
            // 处理上传的文件
            zuoYeRankService.excelFile(file);
            zuoYeSumbitService.importData();
            modelAndView.addObject("success","导入成功！");
        }
        modelAndView.setViewName("zy/success");
        return modelAndView;
    }


    @GetMapping("/downLoad")
    public ResponseEntity<?> downloadExcel(HttpServletResponse response) throws Exception {
        // 创建Workbook
        Workbook workbook = zuoYeRankService.downloadExcel();
        String fileName = "梦想在上杯第三十期实盘比赛_" + HolidayCopy.getRealToday() + ".xlsx";

        // 使用URLEncoder对文件名进行编码
        String encodedFilename = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 设置响应头
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFilename);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 写入响应
        workbook.write(response.getOutputStream());
        workbook.close();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping(value = "/ajaxCheckUserName")
    public void ajaxRequestAddEmail(HttpServletRequest request, HttpServletResponse response,String userName) throws Exception {
        // Object userName = httpSession.get("userName");
        String msg = "";
        Map<String, String> resultMap = new HashMap<>();
        if (!Objects.isNull(userName)) {
            Boolean results = zuoYeRankService.checkUserName(userName.toString());
            if (results) {
                msg = "Success";
            } else {
                String openSwitch = commonService.getValue("ZUO_YE_FIRST_SUMBIT").toString();
                if ("OPEN".equals(openSwitch)) {
                    msg = "Success";
                }else{
                    msg = "用户名不存在";
                }
            }
        } else {
            msg = "请填写用户名";
        }
        resultMap.put("msg", "Success");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        //输出到客户端
        out.println(JSONObject.toJSONString(resultMap));
        out.flush();
        out.close();
    }


}
